﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ExplorerPlus.DomainObjects;
using ExplorerPlus.PluginsInterface;
using ExplorerPlus.Plugins.Common;

namespace ExplorerPlus.Plugins.Movies
{
    public partial class MoviesItemDetailView : UserControl, IItemDetailViewPlugin
    {
        //Control object responsible for rating movie titles.  
        //Workaround: project cannot dynamically build this custom control type
        //                      after using New Project wizard; the control instance is created and sited at runtime instead of 
        //                      adding to design surface.  
        internal ExplorerPlus.Controls.RatingPickerControl ratingPickerControl =
            new ExplorerPlus.Controls.RatingPickerControl();

        Item movie;
        bool blnHasChanges = false;

        public MoviesItemDetailView()
        {
            InitializeComponent();
            this.webBrowser1.AllowNavigation = false;
            this.webBrowser1.AllowWebBrowserDrop = false;
            this.webBrowser1.WebBrowserShortcutsEnabled = false;
        }

        #region IItemDetailViewPlugin Members

        public UserControl ItemDetailView
        {
            get { return this; }
        }

        public bool HasChanges
        {
            get { return blnHasChanges; }
            set { blnHasChanges = value; }
        }

        public void Initialize(Item item)
        {
            movie = item;
            SetMovie();
        }

        bool IItemDetailViewPlugin.Validate()
        {
            if (txtTitle.Text == string.Empty || txtTitle.Text.Trim().Length == 0)
            {
                MessageBox.Show("Please enter movie title.");
                return false;
            }

            return true;
        }

        public Item GetItem()
        {
            GetMovie();
            return movie;
        }

        public Item Store()
        {
            GetMovie();
            blnHasChanges = false;
            new MoviesWebSearchPlugin().DownloadItemImages(movie, Application.StartupPath + "\\Images\\Movies\\");
            //if (movie.ItemId == -1)
            //{
            //    if (movie.GetItemPropertyValue((int)MovieFields.LargeImage).Length > 0)
            //    {
            //        string path = Application.StartupPath + "\\Images\\Movies\\" +
            //            System.IO.Path.GetFileName(
            //            movie.GetItemPropertyValue((int)MovieFields.LargeImage));
            //        pictureBox1.Image.Save(path);
            //        movie.SetItemPropertyValue((int)MovieFields.LargeImage, path);
            //    }
            //}
            return movie;
        }

        public void DragDropFile(string[] filePath)
        {
            movie.FilePath = filePath[0];
            txtFilePath.Text = movie.FilePath;
        }

        #endregion

        private void SetMovie()
        {
            txtTitle.Text = movie.ItemName;
            txtFilePath.Text = movie.FilePath;
            txtActors.Text = movie.GetItemPropertyValue((int)MovieFields.Actor);
            txtDirectors.Text = movie.GetItemPropertyValue((int)MovieFields.Director);
            txtWriters.Text = movie.GetItemPropertyValue((int)MovieFields.Writer);
            txtProducers.Text = movie.GetItemPropertyValue((int)MovieFields.Producer);
            txtRating.Text = movie.GetItemPropertyValue((int)MovieFields.AudienceRating);
            txtRunTime.Text = movie.GetItemPropertyValue((int)MovieFields.RunTime);
            txtSalesRank.Text = movie.GetItemPropertyValue((int)MovieFields.SalesRank);
            txtListPrice.Text = movie.GetItemPropertyValue((int)MovieFields.ListPrice);
            txtStudio.Text = movie.GetItemPropertyValue((int)MovieFields.ProductionStudio);
            txtReleaseDate.Text = movie.GetItemPropertyValue((int)MovieFields.ReleaseDate);
            pictureBox1.ImageLocation = movie.GetItemPropertyValue((int)MovieFields.LargeImage);
            if (webBrowser1.Document != null)
            {
                webBrowser1.Document.Body.InnerHtml =
                    "<html><body  style='font-family:Tahoma; font-size=10pt'>"
                    + movie.GetItemPropertyValue((int)MovieFields.EditorialReviews)
                    + "</body></html>";
            }
            else
            {
                webBrowser1.DocumentText =
                    "<html><body  style='font-family:Tahoma; font-size=10pt'>"
                    + movie.GetItemPropertyValue((int)MovieFields.EditorialReviews)
                    + "</body></html>";
            }

            SetRating();
            RegisterValueChangesEvent(this);
        }

        private void GetMovie()
        {
            movie.ItemName = txtTitle.Text;
            movie.FilePath = txtFilePath.Text;
            movie.SetItemPropertyValue((int)MovieFields.AudienceRating, txtRating.Text);
            movie.SetItemPropertyValue((int)MovieFields.RunTime, txtRunTime.Text);
            movie.SetItemPropertyValue((int)MovieFields.SalesRank, txtSalesRank.Text);
            movie.SetItemPropertyValue((int)MovieFields.ListPrice, txtListPrice.Text);
            movie.SetItemPropertyValue((int)MovieFields.ProductionStudio, txtStudio.Text);
            movie.SetItemPropertyValue((int)MovieFields.ReleaseDate, txtReleaseDate.Text);
            movie.SetItemPropertyValue((int)MovieFields.Rating, ratingPickerControl.CurrentRating.ToString());
            PluginHelper.ExtractValueList(movie, (int)MovieFields.Actor, txtActors.Text);
            PluginHelper.ExtractValueList(movie, (int)MovieFields.Director, txtDirectors.Text);
            PluginHelper.ExtractValueList(movie, (int)MovieFields.Producer, txtProducers.Text);
            PluginHelper.ExtractValueList(movie, (int)MovieFields.Writer, txtWriters.Text);
            if (movie.GetItemPropertyValue((int)MovieFields.Genre) == "")
            {
                movie.AddItemProperty((int)MovieFields.Genre, "All Movies");
            }
        }

        #region Register form controls editing
        private void RegisterValueChangesEvent(Control ctl)
        {
            if (ctl.HasChildren)
            {
                foreach (Control child in ctl.Controls)
                {
                    RegisterValueChangesEvent(child);
                }
            }
            else
                RegisterControlGenericEvent(ctl);
        }

        private void RegisterControlGenericEvent(Control ctl)
        {
            if (ctl is Label)
                return;
            else if (ctl is TextBox || ctl is ComboBox || ctl is DateTimePicker)
            {
                ctl.TextChanged += new EventHandler(ctl_TextChanged);
                return;
            }
            else if (ctl is RadioButton)
            {
                ((RadioButton)ctl).CheckedChanged += new EventHandler(ctl_TextChanged);
            }
        }

        void ctl_TextChanged(object sender, EventArgs e)
        {
            blnHasChanges = true;
        }
        #endregion

        private void lnkVisitPage_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            ExplorerPlus.Plugins.Common.PluginHelper.VisitPage(movie.GetItemPropertyValue((int)MovieFields.DetailPageUrl));
        }

        private void lnkOpenFile_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            ExplorerPlus.Plugins.Common.PluginHelper.OpenFile(movie.FilePath);
        }

        private void lnkOpenDirectory_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            ExplorerPlus.Plugins.Common.PluginHelper.OpenDirectory(movie.FilePath);
        }

        private void btnOpen_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                txtFilePath.Text = openFileDialog1.FileName;
                movie.FilePath = openFileDialog1.FileName;
            }
        }

        private void MoviesItemDetailView_Load(object sender, EventArgs e)
        {
            //dynamically create rating picker control and site on the form
            InitRatingPickerControl();
        }

        /// <summary>
        /// Initializes the rating picker control used on this user control.  
        /// </summary>
        /// <remarks>
        /// Called by ListDetails.Load event.  This special initialization code is not required if the 
        /// RatingPickerControl is built and referenced in a separate control library.  
        /// </remarks>
        private void InitRatingPickerControl()
        {
            //create rating picker control object and site it on the parent user control
            this.panel3.Controls.Add(this.ratingPickerControl);
            //set default properties and data binding
            ((System.ComponentModel.ISupportInitialize)this.ratingPickerControl).BeginInit();
            this.ratingPickerControl.Anchor = (System.Windows.Forms.AnchorStyles)(System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right);
            this.ratingPickerControl.BackColor = System.Drawing.Color.Transparent;
            this.ratingPickerControl.Location = new System.Drawing.Point(55, 216);
            this.ratingPickerControl.Name = "RatingPickerControl1";
            this.ratingPickerControl.Size = new System.Drawing.Size(80, 16);
            this.ratingPickerControl.TabIndex = 1;
            ((System.ComponentModel.ISupportInitialize)this.ratingPickerControl).EndInit();
        }

        private void SetRating()
        {
            if (ratingPickerControl != null)
            {
                string rating = movie.GetItemPropertyValue((int)MovieFields.Rating);
                if (rating != string.Empty || rating != "")
                {
                    double result = -1;
                    if (double.TryParse(rating, out result))
                    {
                        this.ratingPickerControl.CurrentRating = (int)result;
                    }
                }
                else
                {
                    this.ratingPickerControl.CurrentRating = -1;
                }
            }

            string customerRating =
                movie.GetItemPropertyValue((int)MovieFields.TotalCustomerReviews);

            if (customerRating != string.Empty || customerRating != "")
            {
                this.lblCustomerReviews.Text = "(" + customerRating + ")";
            }
        }

    }
}
